/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using MyPhotoIndex.Interfaces;
using MyPhotoIndex.Plugins.ImageFormatProviders;
using System.IO;
using MyPhotoIndex.DataAccess;
using MyPhotoIndex.Utilities;
using MyPhotoIndex.Controls;
using System.Windows.Forms;
using MyPhotoIndex.Settings;
using MyPhotoIndex.Plugins.DataProviders;
using MyPhotoIndex.Interfaces.ImageFormatProviders;
using MyPhotoIndex.ImageBank;
using System.Data.OleDb;

namespace MyPhotoIndex
{
    sealed class PhotoIndexUpgrader
    {
        private const int m_dbVersion = 7;
        private AsyncProgressForm m_progressForm;

        public bool NeedUpgrade()
        {
            IImagesDataAccessProvider dataProvider = (IImagesDataAccessProvider)DataAccessProvider.Instance;
            int curentDbVersion = dataProvider.GetDbVersionNumber();
            if (curentDbVersion < m_dbVersion)
            {
                return true;
            }

            return false;
        }

        public void UpgradePhotoIndexData(AsyncProgressForm progressForm)
        {
            Cursor.Current = Cursors.WaitCursor;

            IImagesDataAccessProvider dataProvider = (IImagesDataAccessProvider)DataAccessProvider.Instance;
            int curentDbVersion = dataProvider.GetDbVersionNumber();

            #region curentDbVersion == 0
            if (curentDbVersion == 0)
            {
                using (OleDbDataReader reader = dataProvider.GetPhotoIndexData())
                {
                    while (reader.Read())
                    {
                        int imageId = reader.GetInt32((int)ImageDataSourceColumnId.Id);
                        String fileName = reader.GetString((int)ImageDataSourceColumnId.FullPath);
                        String extention = Path.GetExtension(fileName).Remove(0, 1);
                        IImageFormatProvider provider = ImageFormatProviders.Default[extention];


                        #region Update image signature & image lastmodifiedDates
                        try
                        {
                            if (provider.Exists(fileName) == true)
                            {
                                //  String signature = provider.GetImageMediaSignature(fileName);
                                DateTime lastModified = provider.GetImageMediaLastUpdated(fileName);

                                ImageDataSourceColumnId[] columns = new ImageDataSourceColumnId[] { /*ImageDataSourceColumnId.FileSignature, */
                                                                                                ImageDataSourceColumnId.LastModified };

                                Object[] data = new object[] { /*signature,*/ lastModified };

                                dataProvider.UpdateImageData(imageId, columns, data);
                            }

                        }
                        catch (FileNotFoundException ex)
                        {
                            Logger.Log(ex);
                            continue;
                        }
                        catch (Exception ex)
                        {
                            Logger.Log(ex);
                        }

                        #endregion

                        if (progressForm != null)
                        {
                            progressForm.Increment();
                        }
                    }
                }

                #region Move old cache to the user documents directory
                try
                {
                    String dbPath = ApplicationSettings.Default.IndexDb;
                    if (String.IsNullOrEmpty(dbPath) == false)
                    {
                        String oldCacheFile = Path.ChangeExtension(dbPath, "icf");

                        String imageCacheFile = ApplicationFolders.CachePath;
                        try
                        {
                            if (Directory.Exists(imageCacheFile) == false)
                            {
                                Directory.CreateDirectory(imageCacheFile);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Log(ex);
                        }

                        String indexId = DataAccessProvider.Instance.GetDbIndexId();
                        imageCacheFile = Path.Combine(imageCacheFile, indexId);
                        imageCacheFile = Path.ChangeExtension(imageCacheFile, "icf");

                        if (File.Exists(imageCacheFile) == false &&
                            File.Exists(oldCacheFile) == true)
                        {
                            File.Copy(oldCacheFile, imageCacheFile);

                        }
                    }

                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
                #endregion
            }
            #endregion

            #region curentDbVersion < 4
            if (curentDbVersion < 4)
            {
                List<SavedQuery> queries = ApplicationSettings.Default.SavedQueries;
                foreach (SavedQuery query in queries)
                {
                    SavedQueriesCollection.Instance.Save(query);
                }

                ApplicationSettings.Default.SavedQueries.Clear();
                ApplicationSettings.Default.Save();
            }
            #endregion

            dataProvider.SetDbVersionNumber(m_dbVersion);
            Cursor.Current = Cursors.Default;
        }

        public bool ImageCacheNeedUpgrade()
        {
            return Storage.Instance.ImageCacheNeedUpgrade();
        }

        public void UpgradeImageCache(AsyncProgressForm progressForm)
        {
            Cursor.Current = Cursors.WaitCursor;
            m_progressForm = progressForm;

            EventHandler<ImageCollectionProgressEventArgs> eventhandler = new EventHandler<ImageCollectionProgressEventArgs>(Instance_ImageCollectionProgressEvent);
            Storage.Instance.ImageCollectionProgressEvent += eventhandler;
            Storage.Instance.UpgradeImageCache();
            Storage.Instance.ImageCollectionProgressEvent -= eventhandler;

            Cursor.Current = Cursors.Default;
        }

        void Instance_ImageCollectionProgressEvent(object sender, ImageCollectionProgressEventArgs e)
        {
            if (m_progressForm != null)
            {
                m_progressForm.Maximum = e.Maximum;
                m_progressForm.Value = e.Value;
            }
        }
    }
}
